package com.vipheyue.huaxue.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.orhanobut.logger.Logger;
import com.vipheyue.huaxue.R;
import com.vipheyue.huaxue.adapter.BaseRecyclerAdapter;
import com.vipheyue.huaxue.adapter.BaseRecyclerViewHolder;
import com.vipheyue.huaxue.bean.EventBean;
import com.vipheyue.huaxue.fragment.DrawerFragment;
import com.vipheyue.huaxue.utils.GsonUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

public class Main2Activity extends AppCompatActivity implements OnRefreshListener, OnLoadMoreListener {

    @Bind(R.id.ivSpeed)
    ImageView ivSpeed;
    @Bind(R.id.ivRefresh)
    ImageView ivRefresh;
    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;
    @Bind(R.id.progressbar)
    ProgressBar progressbar;
    @Bind(R.id.ivSuccess)
    ImageView ivSuccess;
    @Bind(R.id.tvLoadMore)
    TextView tvLoadMore;
    @Bind(R.id.swipeToLoadLayout)
    SwipeToLoadLayout swipeToLoadLayout;
    @Bind(R.id.fab)
    FloatingActionButton fab;
    @Bind(R.id.main_left_drawer_layout)
    RelativeLayout main_left_drawer_layout;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawer_layout;
    @Bind(R.id.iv_Menu_leftImg)
    ImageView iv_Menu_leftImg;
    @Bind(R.id.tv_Menu_leftTitle)
    TextView tv_Menu_leftTitle;

    @Bind(R.id.tv_Menu_Title)
    TextView tv_Menu_Title;
    @Bind(R.id.iv_menu_rightTitle)
    TextView iv_menu_rightTitle;

    @Bind(R.id.rl_menu_right)
    RelativeLayout rl_menu_right;
    @Bind(R.id.swipe_target)
    LinearLayout swipe_target;
    @Bind(R.id.rl_menu_left)
    RelativeLayout rl_menu_left;
    @Bind(R.id.iv_menu_right)
    ImageView iv_menu_right;
    private int nowPageNum = 0;
    private int pageSize = 100;
    private BaseRecyclerAdapter adapter;
    private List<EventBean> mdata = new ArrayList<EventBean>();
    private PopupWindow popWindow;
    private View popWindowLayout;
    Boolean popWinShowing=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ButterKnife.bind(this);
        tv_Menu_Title.setText("继保自动化经验分享");
        tv_Menu_Title.setTextSize(10);
        iv_menu_right.setVisibility(View.VISIBLE);
        iv_menu_right.setImageResource(R.drawable.person);
        iv_Menu_leftImg.setImageResource(R.drawable.lineback);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        popWindowLayout = this.getLayoutInflater().inflate(R.layout.popup_slide_from_bottom, null);
        assert fab != null;
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

//        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
//                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
//        drawer.setDrawerListener(toggle);
//        toggle.syncState();


        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.main_left_drawer_layout, new DrawerFragment());
        ft.commit();

        initview();
    }

    private void initview() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerview.setLayoutManager(layoutManager);//设置显示方式
        adapter = new BaseRecyclerAdapter<EventBean>(this, mdata, R.layout.job_item_main2) {
            @Override
            public void init(BaseRecyclerViewHolder holder, EventBean bean, int position) {
                holder.setText(R.id.tv_jobTitile, bean.getTitile());
                holder.setText(R.id.tv_workAreaType, bean.getLoc());
                holder.setText(R.id.tv_princalPeople, bean.getPrincalPeople());
                holder.setText(R.id.tv_createTime, bean.getUpdatedAt());
            }
        };

        adapter.setOnItemClickLinster(new BaseRecyclerAdapter.OnItemClickLinster() {
            @Override
            public void onItemClick(View view, int position) {
                EventBean job = mdata.get(position);
                String jobStr = GsonUtils.toJson(job);
                Intent intent = new Intent(Main2Activity.this, DetailMessageActivity.class);
                intent.putExtra("jobStr", jobStr);
                Logger.d(jobStr);
                startActivity(intent);
            }
        });
        recyclerview.setAdapter(adapter);//设置适配器

//        swipeToLoadLayout.setSwipeStyle(SwipeToLoadLayout.STYLE.ABOVE);
        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);

        swipeToLoadLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeToLoadLayout.setRefreshing(true);
            }
        });
    }

    @Override
    public void onLoadMore() {
        setData(nowPageNum);
    }

    @Override
    public void onRefresh() {
        mdata.clear();
        nowPageNum = 0;
        setData(nowPageNum);
    }

    private void setData(int getNumPage) {
        BmobQuery<EventBean> query = new BmobQuery<EventBean>();
        query.order("-updatedAt");
        query.setLimit(pageSize); // 限制最多10条数据结果作为一页
        query.setSkip(pageSize * getNumPage); // 忽略前10条数据（即第一页数据结果）
        query.include("releaseUser");// 希望在查询帖子信息的同时也把发布人的信息查询出来

        //TODO 这里要不要加学校限制
        query.findObjects(this, new FindListener<EventBean>() {
            @Override
            public void onSuccess(List<EventBean> object) {
                Logger.d("size...." + object.size());
                mdata.addAll(object);
                nowPageNum = nowPageNum + 1;
                // Call onRefreshComplete when the list has been refreshed.
                adapter.notifyDataSetChanged();
                swipeToLoadLayout.setRefreshing(false);
                swipeToLoadLayout.setLoadingMore(false);
            }

            @Override
            public void onError(int code, String msg) {
                adapter.notifyDataSetChanged();
                swipeToLoadLayout.setRefreshing(false);
                swipeToLoadLayout.setLoadingMore(false);
            }
        });
    }

    @OnClick({R.id.rl_menu_left, R.id.iv_menu_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_menu_left:
                drawer_layout.openDrawer(GravityCompat.START);
                break;
            case R.id.iv_menu_right:
                    initPopWindow();
                break;
        }
    }

    private void initPopWindow() {
        popWindow = new PopupWindow(popWindowLayout, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);


        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());

        // 在底部显示
        popWindow.showAtLocation(Main2Activity.this.findViewById(R.id.fab),
                Gravity.TOP, 0, 100);
        popWindowLayout.findViewById(R.id.tv_1).setOnClickListener(new PopOnClickListener());
        popWindowLayout.findViewById(R.id.tv_2).setOnClickListener(new PopOnClickListener());
        popWindowLayout.findViewById(R.id.tv_3).setOnClickListener(new PopOnClickListener());
        popWindowLayout.findViewById(R.id.tv_4).setOnClickListener(new PopOnClickListener());
        popWindowLayout.findViewById(R.id.tv_5).setOnClickListener(new PopOnClickListener());
        popWindowLayout.findViewById(R.id.tv_6).setOnClickListener(new PopOnClickListener());
        popWindowLayout.findViewById(R.id.tv_7).setOnClickListener(new PopOnClickListener());
        popWindowLayout.findViewById(R.id.tv_8).setOnClickListener(new PopOnClickListener());
        popWindowLayout.findViewById(R.id.btn_login).setOnClickListener(new PopOnClickListener());
        popWindowLayout.findViewById(R.id.iv_close).setOnClickListener(new PopOnClickListener());
        popWinShowing=true;
    }


    public class PopOnClickListener implements View.OnClickListener {

        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.tv_1:
                    goActivity("规范性文件");
                    break;
                case R.id.tv_2:
                    goActivity("消缺经验");
                    break;
                case R.id.tv_3:
                    goActivity("手艺示范");
                    break;
                case R.id.tv_4:
                    goActivity("工作备忘");
                    break;
                case R.id.tv_5:
                    goActivity("各类信息");
                    break;
                case R.id.tv_6:
                    goActivity("作业风险评估及防范");
                    break;
                case R.id.tv_7:
                    goActivity("财经");
                    break;
                case R.id.tv_8:
                    goActivity("财经");
                    break;
                case R.id.line:
                    goActivity("财经");
                    break;
                case R.id.btn_login:
                    popWindow.dismiss();
                    popWinShowing=false;
                    startActivity(new Intent(Main2Activity.this, LoginActivity.class));
                    break;
                case R.id.iv_close:
                    popWinShowing=false;
                    popWindow.dismiss();
                    break;
            }
        }

    }

    public void goActivity(String type) {
        Intent intent = new Intent(Main2Activity.this, TypeActivity.class);
        intent.putExtra("type", type);
        startActivity(intent);
    }

}
